package com.zl.csMall.mine.history.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zl.csMall.code.config.token.TokenTriggerAspect;
import com.zl.csMall.mine.history.service.HistoryService;
import com.zl.csMall.mine.user.po.User;
import com.zl.csMall.mine.user.service.UserService;
import com.zl.csMall.vo.ReturnModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @description: HistoryController
 * @author: ChenNing
 * @date 2025-10-24 10:59
 */
@CrossOrigin(origins = "*")
@Api(tags = "历史浏览记录")
@RestController
@RequestMapping("csMall/mine/history")
public class HistoryController {

    @Autowired
    private HistoryService historyService;
    @Autowired
    private UserService userService;


    /**
     * @description: 查询商品访客记录（全部用户，按浏览时间排序）
     * @param commodityId 商品ID
     * @author ChenNing
     * @date: 2025-10-23 10:49
     */
    @TokenTriggerAspect
    @ApiOperation(value = "查询商品访客记录 - 商家", response = User.class)
    @ApiImplicitParam(name = "commodityId", value = "商品ID", required = true)
    @CrossOrigin("*")
    @GetMapping("comm")
    public ReturnModel getVisitorRecords(@RequestHeader(required = false) String token,
                                         @RequestParam("commodityId") Long commodityId,
                                         @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize){
        // 历史浏览查询指定商品的浏览用户
        Page page = historyService.getUserIdByCommodityId(commodityId, new Page<>(pageNum, pageSize));
        List<Long> userIdList = page.getRecords();
        if (userIdList == null || userIdList.size() < 1){
            return new ReturnModel(new Page<>(pageNum, pageSize));
        }

        LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
        userQuery.select(User::getId, User::getName, User::getWxAvatarUrl);
        int index = 0;
        for (long userId : userIdList){
            if (index == 0){
                userQuery.eq(User::getId, userId);
            } else {
                userQuery.or().eq(User::getId, userId);
            }
            index++;
        }
        List<Map<String, Object>> userList = userService.listMaps(userQuery);
        return new ReturnModel(page.setRecords(userList));
    }

}
